// 预订支付
import {
  getPayInfo,
  queryOrder,
  getAccount,
  getAccountPayConfig,
  balancePay
} from "../api/member";

module.exports = Behavior({
  data: {
    accountInfo: {},
    accountPayRule: {}
  },
  ready: function () {
    this.$pay = this.selectComponent("#pay");
    if (this.$pay) {
      this.getAccountInfo();
    }
  },
  methods: {
    getAccountInfo() {
      getAccount().then(res => {
        this.setData({ _accountInfo: res.data })
      })
      getAccountPayConfig().then(res => {
        this.setData({ _accountPayRule: res.data })
      })
    },
    toMemberPay(options) {
      let { orderNo, payFee, hasDiscount, payChannels } = options;
      if (payChannels.length === 1 && payChannels[0] === "wx") {
        // 微信支付
        return new Promise(((resolve, reject) => {
          this.setData({ payResolve: resolve, payReject: reject });
          this.startWxPay(orderNo);
        }))
      }
      if (payFee === 0) {
        // 直接发起余额支付
        return new Promise(((resolve, reject) => {
          this.setData({ payResolve: resolve, payReject: reject });
          this.startBalancePay(orderNo, "");
        }))
      }
      return new Promise(((resolve, reject) => {
        this.setData({ payResolve: resolve, payReject: reject });
        if (payFee === 0) {
          // 0 元支付
          this.startWxPay(orderNo);
        }
        let accountPayRule = this.data._accountPayRule;
        let accountInfo = this.data._accountInfo;
        let account = { balance: 0, canUseDiscount: false, requirePassword: false }
        if (accountInfo&&accountPayRule.useBalanceScope.indexOf(1) !=-1) {
          account = {
            balance: (accountInfo.balance||0)+(accountInfo.giftBalance||0)-(accountInfo.lockedBalance||0)-(accountInfo.lockedGiftBalance||0),
            canUseDiscount: accountPayRule.canUseDiscount,
            requirePassword: accountPayRule.canSkipPwd ? payFee > accountPayRule.skipPwdAmount : true
          }
        }
        this.$pay.openPay({
          payChannels: payChannels, account: account, payFee: payFee, hasDiscount: hasDiscount,
          confirm: (payChannel, password) => {
            if (payChannel === 'wx') {
              this.startWxPay(orderNo)
            } else {
              this.startBalancePay(orderNo, password)
            }
          },
          cancel: () => {
            // 用户取消支付, 跳转到订单详情页
            this._payFail();
          }
        })
      }))
    },
    startWxPay(orderNo) {
      let data = {
        orderCode: orderNo
      }
      getPayInfo(data).then(res => {
        if (res.code === 0) {
          wx.requestPayment({
            'timeStamp': res.data.payTimestamp + '',
            'nonceStr': res.data.payNonceStr,
            'package': res.data.payPackage,
            'signType': res.data.paySignType,
            'paySign': res.data.paySignature,
            success: (res) => {
              this.startPollOrderStatus(orderNo);
            },
            fail: (res) => {
              // 用户取消支付, 允许用户重新发起支付
              if (this.$pay && this.$pay.data.visible) {
                this.$pay.hideLoading();
                wx.showToast({ title: "用户取消支付", icon: "none", duration: 1500 })
              } else {
                this._payFail();
              }
            }
          })
        } else {
          this._payFail()
        }
      })
    },
    startBalancePay(orderNo, password) {
      return balancePay({ orderCode: orderNo, password }).then(res => {
        if (res.code === 0) {
          this.startPollOrderStatus(orderNo);
        } else {
          // 刷新余额
          this.getAccountInfo();
          // 隐藏支付loading, 允许用户重新发起支付
          this.$pay.resetPassword();
          this.$pay.hideLoading();
          wx.showToast({ title: res.msg, icon: "none", duration: 4000 })
        }
      }).catch(() => {
        this._payFail();
      })
    },
    startPollOrderStatus(orderNo) {
      //
      if (this.$pay) {
        this.$pay.showLoading()
      } else {
        wx.showLoading({title: "订单结果查询中...", mask: true});
      }
      this.setData({ queryTimes: 1 });
      this.innerQuery(orderNo);
    },
    innerQuery(orderNo) {
      if (this.data.queryTimes > 20) {
        this._payFail("查询支付状态超时");
        return;
      }
      queryOrder({ orderCode: orderNo }).then(res => {
        if (res.code !== 0) {
          this.setData({ queryTimes: this.data.queryTimes + 1 });
          setTimeout(() => {
            this.innerQuery(orderNo);
          }, 2000)
          return;
        }
        let payStatus = res.data.code;
        if (payStatus === 100) {
          this._paySuccess();
        } else if (payStatus === 102) {
          this.setData({ queryTimes: this.data.queryTimes + 1 });
          setTimeout(() => {
            this.innerQuery(orderNo);
          }, 2000)
        } else if (payStatus === 104) {
          this._payFail("支付失败,请重试");
        }
      })
    },
    _paySuccess() {
      if (this.$pay) {
        this.$pay.close()
      } else {
        wx.hideLoading();
      }
      this.data.payResolve();
    },
    _payFail(msg) {
      if (this.$pay) {
        this.$pay.hideLoading()
      } else {
        wx.hideLoading();
      }
      if (msg) {
        wx.showToast({ title: msg, icon: "none", duration: 3000 })
      }
      this.data.payReject(msg)
    }
  }
})
